package cc.eddic.pratice.programmingparadigms.nginxlog.impl;

import cc.eddic.pratice.programmingparadigms.nginxlog.LogItem;
import cc.eddic.pratice.programmingparadigms.nginxlog.LogItemParser;
import cc.eddic.pratice.programmingparadigms.nginxlog.NginxLogItem;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Optional;

public class LogItemParserWqjImpl implements LogItemParser {

    private LocalDateTime parseDateTime(String dateTimeString) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        return LocalDateTime.parse(dateTimeString, formatter);
    }

    @Override

    public Optional<LogItem> parse(NginxLogItem nginxLogItem) {
        try {
            String ip = nginxLogItem.getIp();
            LocalDateTime time = parseDateTime(nginxLogItem.getTime());

            String[] requestDetails = extractRequestDetails(nginxLogItem);
            if (requestDetails == null) {
                // 请求字段illegal
                return Optional.empty();
            }
            String method = requestDetails[0];
            String path = requestDetails[1];
            String protocol = requestDetails[2];

            int status = Integer.parseInt(nginxLogItem.getStatus());
            long bytes = Long.parseLong(nginxLogItem.getBytes());
            String referer = nginxLogItem.getReferer();
            String userAgent = nginxLogItem.getUserAgent();

            return Optional.of(new LogItem(ip, time, method, path, null, protocol, status, bytes, referer, userAgent));
        } catch (Exception e) {
            e.printStackTrace();
            return Optional.empty();
        }
    }


    public String[] extractRequestDetails(NginxLogItem nginxLogItem) {
        String request = nginxLogItem.getRequest();
        String[] requestDetails = request.split("\\s+", 3);

        if (requestDetails.length == 3) {
            String method = requestDetails[0]; // 请求方法
            String url = requestDetails[1]; // 请求路径和查询字符串
            String protocol = requestDetails[2]; // 协议

            String path;
            if (url.contains("?")) {
                int index = url.indexOf('?');
                path = url.substring(0, index);
            } else {
                path = url;
            }

            return new String[]{method, path, protocol};

        }

        return null;

    }


}
